/* @flow */

import {
  isDef,
  isUndef,
  isPlainObject
} from '../../../../util/index'

function renderClass( a,b){
  let str = ''
  if(isUndef(b)){
    str = a?a: ''
  }else if(typeof b === 'string' ){
    return b
  }else if(isPlainObject(b)){
    for (const key in b) {
      const val = !!b[key];
      if(val){
        str += key + ' '
      }
    }
  }else if(Array.isArray(b)){
    for (const item of b) {
      if(typeof item === 'string'){
        str += item + ' '
      }else if(isPlainObject(item)){
        str += renderClass('', item)
      } 
    }
  }
  
  return str
}

function updateClass(oldVnode, vnode) {
  const el = vnode.elm
  const data = vnode.data
  const oldData = oldVnode.data
  if (
    isUndef(data.staticClass) &&
    isUndef(data.class) && (
      isUndef(oldData) || (
        isUndef(oldData.staticClass) &&
        isUndef(oldData.class)
      )
    )
  ) {
    return
  }

  let cls 
  if (isDef(data.staticClass) || isDef(data.class)) {
    cls = renderClass(data.staticClass, data.class)
  }

  if (cls !== el._prevClass) {
    el.setAttribute('class', cls)
    el._prevClass = cls
  }
}

export default {
  create: updateClass,
  update: updateClass
}
